import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import apiList from './index'

const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : '/'
// create an axios instance
const request = axios.create({
  baseURL: baseUrl, // api 的 base_url
  withCredentials: true, // 跨域请求时发送 cookies
  timeout: 60000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
  },
})

// request interceptor
request.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    if (sessionStorage.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    // Do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const res = response.data
    const message = res.msg || 'error'
    if (res.code !== 0) {
      const reject = Promise.reject(message || 'error')
      Message({
        type: 'error',
        duration: 5 * 1000,
        dangerouslyUseHTMLString: true,
        message: `<pre>${message}</pre>`,
      })
      // 401 未登录或登录超时，请重新登录;
      if (res.code === 401) {
        // 退出登录逻辑
        return reject
      }
      return reject
    } else {
      return res
    }
  },
  (error) => {
    console.log('error:' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)
// 兼容原先写法 重写get、post
const instance = {
  get: request.get,
  post: request.post,
}
// 重写 get
request.get = function (api, params, config) {
  return instance.get(api, {
    params,
    ...config,
  })
}
// 重写 post
request.post = function (api, params, config) {
  const data = {
    ...params,
  }
  // 兼容上传请求
  if (config && config.headers && config.headers['Content-Type'] === 'multipart/form-data') {
    const forms = new FormData()
    Object.keys(data).forEach((key) => {
      forms.append(key, data[key])
    })
    return instance.post(api, forms, config)
  }
  return instance.post(api, qs.stringify(data), config)
}
// 将api打入axios中 使其直接调用
Object.keys(apiList).forEach((key) => {
  const { url, method, ...rest } = apiList[key]
  const commonOpt = ['get', 'post', 'put', 'patch']
  request[key] = function (data, config) {
    let fn = request[method]
    const conf = {
      ...rest,
      ...config,
    }
    return commonOpt.includes(method)
      ? fn(url, data, conf)
      : fn(url, {
          params: data,
          ...conf,
        })
  }
})
export default request
